package com.inspur.dgov.vlbod.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.weixin.WeiXinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/weixin")
public class WeixinController {

    @Autowired
    private WeiXinService weiXinService;

    @PostMapping("/config")
    public DgovResponse weixinConfig(HttpServletRequest request, @RequestBody JSONObject data) {
        JSONObject json = new JSONObject();
        try {
            String signUrl = URLDecoder.decode(data.getString("signUrl"), StandardCharsets.UTF_8.toString());
            log.info("signUrl  is {}",signUrl);
            if (StrUtil.isEmpty(signUrl)) {
                log.error("/weixin/config error:signUrl为空");
                return DgovResponse.fail("请求山东通平台签名失败");
            }
            int timestamp = (int) (System.currentTimeMillis() / 1000);
            json.put("timestamp", timestamp);
            String nonceStr = RandomUtil.randomString(16);
            json.put("nonceStr", nonceStr);
            //获取jsapi_ticket（7200秒，redis存储）
            JSONObject ticketJson = this.weiXinService.getTicket();
            if (null == ticketJson) {
                log.error("/weixin/config error:山东通平台临时票据获取失败");
                return DgovResponse.fail("山东通平台配置获取失败");
            }
            String ticket = ticketJson.getString("ticket");
            log.error("ticket is {}",ticket);
            log.error("timestamp is {}",timestamp);
            log.error("nonceStr is {}",nonceStr);
            // 生成签名
            String signature = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + signUrl;
            json.put("signature", SecureUtil.sha1(signature));
            log.error("signature is : {}",json.getString("signature"));
            return DgovResponse.success(json);
        } catch (Exception e) {
            log.error("/weixin/config error:" + e.getMessage());
            return DgovResponse.fail("山东通平台配置获取失败");
        }
    }

    /**
     * 获取山东通平台令牌
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/token")
    public DgovResponse weixinToken(HttpServletRequest request, HttpServletResponse response) {
        try {
            JSONObject jsonObject = this.weiXinService.getToken();
            return DgovResponse.success(jsonObject.getString("access_token"));
        } catch (Exception e) {
            log.error("/weixin/token error:" + e.getMessage());
            return DgovResponse.fail("山东通平台令牌获取失败");
        }
    }
}
